package org.xxpay.mch.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.entity.AgentpayPassage;
import org.xxpay.core.entity.PayInterface;
import org.xxpay.core.entity.PayInterfaceType;
import org.xxpay.mch.common.ctrl.BaseController;
import org.xxpay.mch.config.service.CommonConfigService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author: dingzhiwei
 * @date: 18/05/05
 * @description: 代付通道
 */
@RestController
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/config/agentpay_passage")
public class AgentpayPassageController extends BaseController {

    @Autowired
    private CommonConfigService commonConfigService;

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {

        judgeRecord(); //校验越权操作
        JSONObject param = getJsonParam(request);
        AgentpayPassage agentpayPassage = getObject(param, AgentpayPassage.class);
        agentpayPassage.setBelongInfoType(MchConstant.SYSTYPE_MCH);
        agentpayPassage.setBelongInfoId(getUser().getId());
        int count = commonService.agentpayPassageService.count(agentpayPassage);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<AgentpayPassage> agentpayPassageList = commonService.agentpayPassageService.select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), agentpayPassage);
        // 支付接口类型Map
        Map payInterfaceTypeMap = commonConfigService.getPayInterfaceTypeMap();
        // 支付接口Map
        Map payInterfaceMap = commonConfigService.getPayInterfaceMap();

        // 转换前端显示
        List<JSONObject> objects = new LinkedList<>();
        for(AgentpayPassage info : agentpayPassageList) {
            JSONObject object = (JSONObject) JSON.toJSON(info);
            object.put("ifTypeName", payInterfaceTypeMap.get(info.getIfTypeCode()));    // 转换接口类型名称
            object.put("ifName", payInterfaceMap.get(info.getIfCode()));                // 转换支付接口名称
            objects.add(object);
        }
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(objects, count));
    }

    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer id = getIntegerRequired(param, "id");
        AgentpayPassage agentpayPassage = judgeRecord(id); //校验越权操作
        return ResponseEntity.ok(XxPayResponse.buildSuccess(agentpayPassage));
    }

    @RequestMapping("/update")
    @ResponseBody
    @MethodLog( remark = "修改代付通道" )
    public ResponseEntity<?> update(HttpServletRequest request) {

        AgentpayPassage agentpayPassage = getReqParamObject();
        judgeRecord(agentpayPassage.getId()); //校验越权操作

        String ifCode = agentpayPassage.getIfCode();
        PayInterface payInterface = commonService.payInterfaceService.findByCode(ifCode);
        if(payInterface == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_MGR_PAY_INTERFACE_NOT_EXIST));
        }
        agentpayPassage.setIfTypeCode(payInterface.getIfTypeCode()); // 设置支付接口类型
        int count = commonService.agentpayPassageService.update(agentpayPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/risk_update")
    @ResponseBody
    @MethodLog( remark = "修改代付通道风控" )
    public ResponseEntity<?> updateRisk(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        handleParamAmount(param, "maxDayAmount"); // 元转分
        AgentpayPassage agentpayPassage = getObject(param, AgentpayPassage.class);
        judgeRecord(agentpayPassage.getId()); //校验越权操作
        int count = commonService.agentpayPassageService.update(agentpayPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/rate_update")
    @ResponseBody
    @MethodLog( remark = "修改代付通道费率" )
    public ResponseEntity<?> updateRate(HttpServletRequest request) {

        AgentpayPassage agentpayPassage = getReqParamObject();
        judgeRecord(agentpayPassage.getId()); //校验越权操作
        int count = commonService.agentpayPassageService.update(agentpayPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/add")
    @ResponseBody
    @MethodLog( remark = "新增代付通道" )
    public ResponseEntity<?> add(HttpServletRequest request) {

        judgeRecord(); //校验越权操作

        AgentpayPassage agentpayPassage = getReqParamObject();
        String ifCode = agentpayPassage.getIfCode();
        PayInterface payInterface = commonService.payInterfaceService.findByCode(ifCode);
        if(payInterface == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_MGR_PAY_INTERFACE_NOT_EXIST));
        }
        agentpayPassage.setIfTypeCode(payInterface.getIfTypeCode()); // 设置支付接口类型

        agentpayPassage.setBelongInfoType(MchConstant.SYSTYPE_MCH);
        agentpayPassage.setBelongInfoId(getUser().getId());
        int count = commonService.agentpayPassageService.add(agentpayPassage);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));

    }

    /**
     * 根据代付通道ID,获取支付账号配置定义描述
     * @param request
     * @return
     */
    @RequestMapping("/pay_config_get")
    @ResponseBody
    public ResponseEntity<?> getPayConfig(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Integer agentpayPassageId = getIntegerRequired(param, "agentpayPassageId");
        AgentpayPassage agentpayPassage = judgeRecord(agentpayPassageId); //校验越权操作
        if(agentpayPassage == null) {
            return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
        }
        String ifCode = agentpayPassage.getIfCode();
        String ifTypeCode = agentpayPassage.getIfTypeCode();

        // 如果接口配置了定义描述,则使用接口
        PayInterface payInterface = commonService.payInterfaceService.findByCode(ifCode);
        if(payInterface != null && StringUtils.isNotBlank(payInterface.getParam())) {
            // 支付接口类型Map
            Map payInterfaceTypeMap = commonConfigService.getPayInterfaceTypeMap();
            JSONObject object = (JSONObject) JSON.toJSON(payInterface);
            object.put("ifTypeName", payInterfaceTypeMap.get(payInterface.getIfTypeCode()));
            return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
        }
        // 使用接口类型配置的定义描述
        PayInterfaceType payInterfaceType = commonService.payInterfaceTypeService.findByCode(ifTypeCode);
        if(payInterfaceType != null && StringUtils.isNotBlank(payInterfaceType.getParam())) {
            // 支付接口类型Map
            Map payInterfaceTypeMap = commonConfigService.getPayInterfaceTypeMap();
            JSONObject object = (JSONObject) JSON.toJSON(payInterfaceType);
            object.put("ifTypeName", payInterfaceTypeMap.get(payInterfaceType.getIfTypeCode()));
            return ResponseEntity.ok(XxPayResponse.buildSuccess(object));
        }
        return ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
    }


    /** 校验账号类型和获取的数据是否合法 **/
    private void judgeRecord(){

        //当前登录用户不属于私有商户
        if(this.getUser().getType() != MchConstant.MCH_TYPE_PRIVATE){
            throw new ServiceException(RetEnum.RET_MCH_PERMISSION_ERROR);
        }
    }

    /** 校验账号类型和获取的数据是否合法 **/
    private AgentpayPassage judgeRecord(Integer recordId){

        //当前登录用户是否属于私有商户
        judgeRecord();

        //判断是否越权查看
        AgentpayPassage record = commonService.agentpayPassageService.findById(recordId);
        if(record == null || record.getBelongInfoType() != MchConstant.SYSTYPE_MCH || !record.getBelongInfoId().equals(this.getUser().getId())){
            throw new ServiceException(RetEnum.RET_MCH_PERMISSION_ERROR);
        }
        return record;
    }


    /** 封装获取代付通道 请求参数 （包装成对象类型 & 自动判断费率模式） **/
    private AgentpayPassage getReqParamObject(){

        // 请求参数
        JSONObject param = getJsonParam();

        //去除空格 费率 和 固定费用
        param.replace("feeRate",StringUtils.deleteWhitespace(param.getString("feeRate")));
        param.replace("feeEvery",StringUtils.deleteWhitespace(param.getString("feeEvery")));

        handleParamAmount(param, "feeEvery"); //在getObject进行金额的转换，避免出现 [can not cast to long, value] 异常。
        AgentpayPassage record = getObject(param, AgentpayPassage.class);

        if(record.getFeeType() == MchConstant.FEE_TYPE_RATE) { //费率模式

            //费率设置有误！
            if(record.getFeeRate() == null || record.getFeeRate().compareTo(BigDecimal.ZERO) <= 0){
                throw new ServiceException(RetEnum.RET_COMM_PARAM_ERROR);
            }

            record.setFeeEvery(null);

        }else if(record.getFeeType() == MchConstant.FEE_TYPE_FIX){ //固定费用

            //设置费用有误
            if(record.getFeeEvery() == null || record.getFeeEvery() <= 0){
                throw new ServiceException(RetEnum.RET_COMM_PARAM_ERROR);
            }

            record.setFeeRate(null);

        }else if(record.getFeeType() == MchConstant.FEE_TYPE_RATE_AND_FIX){ //费率模式 + 固定费用

            //费率设置有误！
            if(record.getFeeRate() == null || record.getFeeRate().compareTo(BigDecimal.ZERO) <= 0){
                throw new ServiceException(RetEnum.RET_COMM_PARAM_ERROR);
            }

            //设置费用有误
            if(record.getFeeEvery() == null || record.getFeeEvery() <= 0){
                throw new ServiceException(RetEnum.RET_COMM_PARAM_ERROR);
            }
        }

        return record;
    }


}
